//
//  YBRechargeType.m
//  WuyouTang
//
//  Created by YB007 on 2019/8/22.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBRechargeType.h"
//微信
#import <WXApi.h>
//支付宝
#import "Order.h"
#import <AlipaySDK/AlipaySDK.h>
#import "DataSigner.h"
#import "DataVerifier.h"
//苹果内购
#import <StoreKit/StoreKit.h>

//#import "BraintreePayPal.h"
//,BTViewControllerPresentingDelegate
@interface YBRechargeType()<WXApiDelegate,SKProductsRequestDelegate,SKPaymentTransactionObserver>
{
    NSString *shortDesc;
    NSDictionary *paypalSelDic;
    
    RechargeType chargeType;
}
//内购参数
@property (nonatomic,strong) SKProductsRequest *request;
@property (nonatomic,strong) NSArray *products;
@property (nonatomic,strong) NSSet *productIdentifiers;
@property (nonatomic,strong) NSMutableSet *purchasedProducts;
@property (nonatomic,strong) SKProduct *product;
@property (nonatomic,copy) NSString *OrderNo;
//@property (strong, nonatomic) BTPayPalDriver *payPalDriver;
@property (nonatomic,strong)NSString *braintreeStr;


@end

@implementation YBRechargeType

static YBRechargeType *chargeManeger = nil;

+(instancetype)chargeManeger {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        chargeManeger = [[super allocWithZone:NULL]init];
    });
    return chargeManeger;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self chargeManeger];
}
#pragma mark - 监听支付宝、微信支付通知
-(void)addPayNotice {
    //微信、支付宝回调通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxPayNot:) name:@"wxPayNot" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aliPayNot:) name:@"aliPayNot" object:nil];
}
-(void)wxPayNot:(NSNotification *)noti {
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"rk_paying"];
    NSDictionary *dic = [noti userInfo];
    NSString *code = minstr([dic valueForKey:@"code"]);
    NSString *msg = minstr([dic valueForKey:@"msg"]);
    if ([code isEqual:@"1"]) {
        if (self.payEvent) {
            self.payEvent(0, 0, YZMsg(@"支付成功"));
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:msg];
    });
    
}
-(void)aliPayNot:(NSNotification *)noti {
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"rk_paying"];
    NSDictionary *dic = [noti userInfo];
    NSLog(@"----%@",dic);
    NSString *resultStatus = minstr([dic valueForKey:@"resultStatus"]);
    NSString *msg;
    if ([resultStatus isEqual:@"9000"]) {
        msg = YZMsg(@"支付成功");
        if (self.payEvent) {
            self.payEvent(0, 0, YZMsg(@"支付成功"));
        }
    }else if ([resultStatus isEqual:@"6001"]){
        msg = YZMsg(@"支付取消");
        if (self.payEvent) {
            self.payEvent(-1, 0, YZMsg(@"支付取消"));
        }
    }else{
        msg = YZMsg(@"支付失败");
        if (self.payEvent) {
            self.payEvent(-1, 0, YZMsg(@"支付失败"));
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:msg];
    });
    
}
-(void)removePayNotice{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - 微信
- (void)setWechatAppID:(NSString *)wechatAppID {
    BOOL isOK =  [WXApi registerApp:wechatAppID universalLink:WechatUniversalLink];
    NSLog(@"===%d",isOK);
}

-(void)selWechatPayUrl:(NSString *)url andParameter:(NSDictionary *)parameter complete:(RechargeTypeBlock)complete{
    if (complete) {
        self.payEvent = ^(int stateCode, int payType, NSString *msg) {
            complete(stateCode,payType,msg);
        };
    }
    [MBProgressHUD showMessage:@""];
    YBWeakSelf;
    [WYNetworking postWithUrl:url Dic:parameter Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            NSDictionary *dict = [info firstObject];
            //调起微信支付
            NSString *times = [dict objectForKey:@"timestamp"];
            PayReq* req             = [[PayReq alloc] init];
            req.partnerId           = [dict objectForKey:@"partnerid"];
            NSString *pid = [NSString stringWithFormat:@"%@",[dict objectForKey:@"prepayid"]];
            if ([pid isEqual:[NSNull null]] || pid == NULL || [pid isEqual:@"null"]) {
                pid = @"123";
            }
            req.prepayId            = pid;
            req.nonceStr            = [dict objectForKey:@"noncestr"];
            req.timeStamp           = times.intValue;
            req.package             = [dict objectForKey:@"package"];
            req.sign                = [dict objectForKey:@"sign"];
            [WXApi sendReq:req completion:^(BOOL success) {
                NSLog(@"===%d",success);
                if (!success) {
                    [MBProgressHUD showPop:YZMsg(@"微信调起失败")];
                }
            }];
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"rk_paying"];
        }else {
            [MBProgressHUD showError:msg];
            if (weakSelf.payEvent) {
                weakSelf.payEvent(-1, 0, @"");
            }
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
}
//在APPDelegate监听 通过通知回调
//-(void)onResp:(BaseResp *)resp{
//    //支付返回结果，实际支付结果需要去微信服务器端查询
//    NSString *strMsg = [NSString stringWithFormat:@"支付结果"];
//    switch (resp.errCode) {
//        case WXSuccess:
//            strMsg = @"支付结果：成功！";
//            NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
//            [MBProgressHUD hideHUD];
//            if (self.payEvent) {
//                self.payEvent(0, 0, @"支付成功");
//            }
//            break;
//        default:
//            strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
//            NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
//            [MBProgressHUD hideHUD];
//            if (self.payEvent) {
//                self.payEvent(-1, 0, @"支付失败");
//            }
//            break;
//    }
//}

#pragma mark - 支付宝
-(void)selAliPayUrl:(NSString *)url andParameter:(NSDictionary *)parameter complete:(RechargeTypeBlock)comlete{
    if (comlete) {
        self.payEvent = ^(int stateCode, int payType, NSString *msg) {
            comlete(stateCode,payType,msg);
        };
    }
    NSString *partner = _aliPayPartner;
    NSString *seller =  _aliPaySellerID;
    NSString *privateKey = _aliPayKey;
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0){
        //[MBProgressHUD showError:YZMsg(@"缺少partner或者seller或者私钥")];
        [MBProgressHUD showPop:YZMsg(@"支付宝未接入")];
        if (self.payEvent) {
            self.payEvent(-1, 1, @"");
        }
        return;
    }
    if ([PublicObj checkNull:_aliCallBackUrl]) {
        [MBProgressHUD showError:YZMsg(@"请填写回调地址")];
        if (self.payEvent) {
            self.payEvent(-1, 1, @"");
        }
        return;
    }
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    
    YBWeakSelf;
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:url Dic:parameter Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"rk_paying"];
            NSString *infos = [[info firstObject] valueForKey:@"orderid"];
            order.tradeNO = infos;
            order.notifyURL = _aliCallBackUrl; //[h5url stringByAppendingString:@"/Appapi/Pay/notify_ali"];
            order.amount = minstr([parameter valueForKey:@"money"]);
            order.productName = [NSString stringWithFormat:@"%@%@",[parameter valueForKey:@"coin"],[common name_coin]];
            if (![PublicObj checkNull:minstr([parameter valueForKey:@"days"])]) {
                //购买会员
                order.productName = [NSString stringWithFormat:@"%@%@",[parameter valueForKey:@"days"],YZMsg(@"会员")];
            }
            order.productDescription = @"productDescription";
            //以下配置信息是默认信息,不需要更改.
            order.service = @"mobile.securitypay.pay";
            order.paymentType = @"1";
            order.inputCharset = @"utf-8";
            order.itBPay = @"30m";
            order.showUrl = @"m.alipay.com";
            //应用注册scheme,在AlixPayDemo-Info.plist定义URL types,用于快捷支付成功后重新唤起商户应用
            NSString *appScheme = [[NSBundle mainBundle] bundleIdentifier];
            //将商品信息拼接成字符串
            NSString *orderSpec = [order description];
            NSLog(@"orderSpec = %@",orderSpec);
            //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
            id<DataSigner> signer = CreateRSADataSigner(privateKey);
            NSString *signedString = [signer signString:orderSpec];
            //将签名成功字符串格式化为订单字符串,请严格按照该格式
            NSString *orderString = nil;
            if (signedString != nil) {
                orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                               orderSpec, signedString, @"RSA"];
                
                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"reslut = %@",resultDic);
                    NSInteger resultStatus = [resultDic[@"resultStatus"] integerValue];
                    NSLog(@"#######%ld",(long)resultStatus);
                    // NSString *publicKey = alipaypublicKey;
                    NSLog(@"支付状态信息---%ld---%@",resultStatus,[resultDic valueForKey:@"memo"]);
                    // 是否支付成功
                    if (9000 == resultStatus) {
                        /*
                         *用公钥验证签名
                         */
                        if (weakSelf.payEvent) {
                            weakSelf.payEvent(0, 1, YZMsg(@"支付成功"));
                        }
                    }else {
                        if (weakSelf.payEvent) {
                            weakSelf.payEvent(-1, 1, YZMsg(@"支付失败"));
                        }
                    }
                }];
            }
        }else {
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}

#pragma mark - 苹果
-(void)selApplePayUrl:(NSString *)url andParameter:(NSDictionary *)parameter complete:(RechargeTypeBlock)complete {
    if (complete) {
        self.payEvent = ^(int stateCode, int payType, NSString *msg) {
            complete(stateCode,payType,msg);
        };
    }
    if ([PublicObj checkNull:_productID]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showError:YZMsg(@"请填写内购产品ID")];
        });
        return;
    }
    if ([PublicObj checkNull:_appleCallBackUrl]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showError:YZMsg(@"请填写内购回调地址")];
        });
        return;
    }
    
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:url Dic:parameter Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSString *infos = [[info firstObject] valueForKey:@"orderid"];
            self.OrderNo = infos;//订单
            //苹果支付ID
            NSString *setStr = minstr(_productID);
            NSSet *set = [[NSSet alloc] initWithObjects:setStr, nil];
            self.request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
            self.request.delegate = self;
            [self.request start];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:msg];
            });
        }
    } Fail:^(id fail) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
    }];
}
-(void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    
    self.products = response.products;
    self.request = nil;
    for (SKProduct *product in response.products) {
        NSLog(@"已获取到产品信息 %@,%@,%@",product.localizedTitle,product.localizedDescription,product.price);
        self.product = product;
    }
    if (!self.product) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [self showAlertView:YZMsg(@"无法获取商品信息")];
        });
        return;
    }
    //3.获取到产品信息，加入支付队列
    SKPayment *payment = [SKPayment paymentWithProduct:self.product];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
            default:
                break;
        }
    }
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    
    //NSLog(@"completeTransaction...");
    [self recordTransaction: transaction];
    [self provideContent: transaction.payment.productIdentifier];
    [self verifyReceipt:transaction];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}
- (void)recordTransaction:(SKPaymentTransaction *)transaction {
    // Optional: Record the transaction on the server side...
    //记录当前购买成功的商品
    // NSLog(@"recordTransaction");
}
- (void)provideContent:(NSString *)productIdentifier {
    // NSLog(@"provideContent %@", productIdentifier);
    //针对购买的商品，提供不同的服务。
    [_purchasedProducts addObject:productIdentifier];
}
#pragma mark 服务器验证购买凭据
- (void)verifyReceipt:(SKPaymentTransaction *)transaction {
    
    //苹果：域名+/Appapi/Pay/notify_ios
    NSURL *url = [NSURL URLWithString:minstr(_appleCallBackUrl)];//[h5url stringByAppendingFormat:@"/Appapi/Pay/notify_ios"]
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    request.HTTPMethod = @"POST";
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    NSData *transData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
    NSString *encodeStr = [transData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    /**
     * 这里获取的是 xcode 中的 build
     * 后台上架版本号和本地 build 相同时视为 沙盒环境否则视为生产环境
     */
    NSString *currentBuild = [PublicObj getAppBuild];
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\",\"version_ios\":\"%@\",\"out_trade_no\" : \"%@\"}", encodeStr,currentBuild,self.OrderNo];
    //把bodyString转换为NSData数据
    NSData *bodyData = [payload dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    [request setHTTPBody:bodyData];
    // 提交验证请求，并获得官方的验证JSON结果
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    YBWeakSelf;
    if (result == nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
        // [MBProgressHUD showError:@"验证失败"];
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
        if(dict==nil){
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:YZMsg(@"请查看网站是否开启了调试模式")];
            });
            return;
        }
        if ([[dict valueForKey:@"status"] isEqual:@"success"]) {
            //比对字典中以下信息基本上可以保证数据安全
            if (weakSelf.payEvent) {
                weakSelf.payEvent(0, 2, YZMsg(@"支付成功"));
            }
        }else{
            if (weakSelf.payEvent) {
                weakSelf.payEvent(-1, 2, minstr([dict valueForKey:@"info"]));
            }
        }
    }
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
    });
    if (transaction.error.code != SKErrorPaymentCancelled) {
        [self showAlertView:transaction.error.localizedDescription];
        NSLog(@"Transaction error: %@", transaction.error.localizedDescription);
    }else{
       
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    [self recordTransaction: transaction];
    [self provideContent: transaction.originalTransaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        [self showAlertView:YZMsg(@"用户已恢复购买")];
    });
    
}

- (void)showAlertView:(NSString *)message{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:YZMsg(@"提示") message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelA = [UIAlertAction actionWithTitle:YZMsg(@"好的") style:UIAlertActionStyleCancel handler:nil];
    UIViewController *currentVC = [UIApplication sharedApplication].delegate.window.rootViewController;
    [alertC addAction:cancelA];
    currentVC.modalPresentationStyle = 0;
    [currentVC presentViewController:alertC animated:YES completion:nil];
}


#pragma mark----paypal支付
//PayPal支付
-(void)selPayPalAndPatameter:(NSDictionary *)parameter rechargeType:(RechargeType)type complete:(RechargeTypeBlock)complete{
    chargeType = type;
    paypalSelDic = parameter;
    if (complete) {
        self.payEvent = ^(int stateCode, int payType, NSString *msg) {
            complete(stateCode,payType,msg);
        };
    }

    [MBProgressHUD showMessage:@""];

    NSDictionary *subdic = @{
                             @"uid":[Config getOwnID],
                             @"token":[Config getOwnToken],
                             };
    [WYNetworking postWithUrl:@"User.getBraintreeToken" Dic:subdic Suc:^(int code, id info, NSString *msg) {

        if (code == 0) {
            NSDictionary *infos =  [info firstObject];
            _braintreeStr =minstr([infos valueForKey:@"braintreeToken"]);
            if (chargeType == rechargeType_Goods) {
                [self selPayPalBuyGoods:paypalSelDic];
            }else{
                [self dopayPal:_braintreeStr];

            }
        }
        else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:msg];
            });

        }

        } Fail:^(id fail) {
            
        }];
    
}
-(void)selPayPalBuyGoods:(NSDictionary *)goodsDic {
    paypalSelDic = goodsDic;
    shortDesc = [NSString stringWithFormat:@"%@%@",minstr([paypalSelDic valueForKey:@"money"]),@"商品"];
    // [self selPaypalParameter:minstr([paypalSelDic valueForKey:@"orderid"])];

}

-(void)dopayPal:(NSString *)braintreeToken{
    NSLog(@"paypal支付");
    
    NSDictionary *subdic = [NSDictionary dictionary];
    NSString *urlStr = @"";
    if (chargeType == rechargeType_Vip) {
        urlStr =@"Vipcharge.getBraintreePaypalOrder";
        subdic = @{
                                 @"uid":[Config getOwnID],
                                 @"token":[Config getOwnToken],
                                 @"chargeid":[paypalSelDic valueForKey:@"chargeid"],
                                 @"days":[paypalSelDic valueForKey:@"days"],
                                 @"money":[paypalSelDic valueForKey:@"money"]
                                 };

    }else{
        urlStr =@"Charge.getBraintreePaypalOrder";
        subdic = @{
                                 @"uid":[Config getOwnID],
                                 @"token":[Config getOwnToken],
                                 @"chargeid":[paypalSelDic valueForKey:@"chargeid"],
                                 @"coin":[paypalSelDic valueForKey:@"coin"],
                                 @"money":[paypalSelDic valueForKey:@"money"]
                                 };
    }
    
    [WYNetworking postWithUrl:urlStr Dic:subdic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            shortDesc = [NSString stringWithFormat:@"%@%@",minstr([paypalSelDic valueForKey:@"coin_paypal"]),[common name_coin]];

            NSDictionary *dict = [info firstObject];
            
            //调起paypal支付
            // [self selPaypalParameter:minstr([dict valueForKey:@"orderid"])];
        }
        else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:msg];
            });

        }

        } Fail:^(id fail) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
            });

        }];
    
}

/*
- (BTPayPalDriver *)payPalDriver
{
    if (!_payPalDriver) {
        //TODO 替换为自己的 token
        BTAPIClient *braintreeClient = [[BTAPIClient alloc] initWithAuthorization:_braintreeStr];
        _payPalDriver = [[BTPayPalDriver alloc] initWithAPIClient:braintreeClient];
        _payPalDriver.viewControllerPresentingDelegate = self;
    }
    return _payPalDriver;
}

-(void)selPaypalParameter:(NSString *)orderIDStr{
    NSString *price = minstr([paypalSelDic valueForKey:@"money"]);
    NSString *orderNo = orderIDStr;
    BTPayPalRequest *request = [[BTPayPalRequest alloc] initWithAmount:price];
    request.currencyCode = @"USD";
    
    BTPayPalLineItem *item = [[BTPayPalLineItem alloc] initWithQuantity:@"1" unitAmount:price name:shortDesc kind:BTPayPalLineItemKindDebit];
    item.productCode = orderNo; //订单编号
    request.lineItems = @[item];
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
    });

    [self.payPalDriver requestOneTimePayment:request completion:^(BTPayPalAccountNonce * _Nullable tokenizedPayPalAccount, NSError * _Nullable error) {
          
        if (tokenizedPayPalAccount) {
            NSLog(@"-->> paypal 支付成功 nonce:%@", tokenizedPayPalAccount.nonce);
            [self BraintreeCallback:orderIDStr nonce:tokenizedPayPalAccount.nonce];
            
            //todo 调用后台接口，传递 tokenizedPayPalAccount.nonce
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
            });

        } else if (error) {
            // Handle error here...
            NSLog(@"paypal 支付失败 ：%@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"支付失败"];
            });

            
        } else {
            // Buyer canceled payment approval
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"支付取消"];
            });

        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });


    }];


}
 
 */

-(void)BraintreeCallback:(NSString *)orderno nonce:(NSString *)nonce{
    
    NSString *ordertype = @"";
    if (chargeType == rechargeType_Vip) {
        ordertype = @"vip_pay";
    }else if (chargeType == rechargeType_coin){
        ordertype = @"coin_charge";
    }else{
        ordertype = @"order_pay";
    }
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"ordertype":ordertype,@"orderno":orderno,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],@"nonce":nonce};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *subdic = @{
                             @"uid":[Config getOwnID],
                             @"token":[Config getOwnToken],
                             @"orderno":orderno,
                             @"ordertype":ordertype,
                             @"nonce":nonce,
                             @"money":minstr([paypalSelDic valueForKey:@"money"]),
                             @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                             @"sign":sign
                             };
    
    [WYNetworking postWithUrl:@"User.BraintreeCallback" Dic:subdic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
//            [MBProgressHUD showError:@"支付成功"];
//            [self requestData];
            if (self.payEvent) {
                self.payEvent(0, 0, YZMsg(@"支付成功"));
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
            });

        }
        else{
            if (self.payEvent) {
                self.payEvent(-1, 0, YZMsg(@"支付失败"));
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
            });

        }

        } Fail:^(id fail) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
            });

        }];
    
}
#pragma mark - BTViewControllerPresentingDelegate
// Required
- (void)paymentDriver:(id)paymentDriver requestsPresentationOfViewController:(UIViewController *)viewController
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
    });
    viewController.modalPresentationStyle = 0;
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:viewController animated:YES completion:nil];
}

// Required
- (void)paymentDriver:(id)paymentDriver requestsDismissalOfViewController:(UIViewController *)viewController
{
    [viewController dismissViewControllerAnimated:YES completion:^{
        [MBProgressHUD hideHUD];
    }];
}

@end
